<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageShopThumb;
use plugin\ycMassage\app\model\MassageRegions;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\validate\MassageShop as ValidateMassageShop;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\Str;
use support\Request;
use think\facade\Db;
use think\facade\Session;

class ShopController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 240
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('title', 'input', '门店搜索', [
            'placeholder' => '门店名称搜索'
        ]);
        $builder->addScreen('examine', 'select', '审核状态', [
            'options' => Examine::getOptions()
        ]);
        $builder->addTopButton('add', '创建门店', [
            'api'       => $this->pluginPrefix . '/admin/Shop/create',
            'path' => '/Shop/create',
            'type'      => 'modal'
        ], [
            'title' => '创建门店',
        ], [
            'type' => 'success'
        ]);
        /* $builder->addRightButton('control', '控制台', [
            'api'    => $this->pluginPrefix . '/admin/Shop/control',
            'path' => '/Shop/control'
        ], [], [
            'type' => 'success',
            'link' => true
        ]); */
        $builder->addRightButton('examine', '审核', [
            'api'    => $this->pluginPrefix . '/admin/Shop/examine',
            'path' => '/Shop/examine',
            'type'      => 'modal',
            'params' => [
                'field' => 'examine',
                'where' => '=',
                'value' => 0
            ]
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addRightButton('edit', '修改', [
            'api'    => $this->pluginPrefix . '/admin/Shop/update',
            'path' => '/Shop/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('thumb', '图册', [
            'api'    => $this->pluginPrefix . '/admin/ShopThumb/index',
            'path' => '/ShopThumb/index',
            'aliasParams' => [
                'id' => 'shop_id'
            ]
        ], [], [
            'type' => 'success',
            'link' => true
        ]);
        $builder->addRightButton('control', '管理', [
            'type'   => 'link',
            'api'    => $this->pluginPrefix . '/admin/Shop/control'
        ], [], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumnEle('headimg', '店长头像', [
                'width' => 80,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '店长昵称', [
                'width' => 120,
            ])
            ->addColumn('mch_title', '商户名称', [
                'width' => 120,
            ])
            ->addColumn('title', '门店名称', [
                'width' => 120,
            ])
            ->addColumn('tel', '门店联系电话', [
                'width' => 120,
            ])
            ->addColumn('name', '负责人', [
                'width' => 120,
            ])
            ->addColumn('mobile', '联系电话', [
                'width' => 120,
            ])
            ->addColumnEle('examine', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => Examine::dictOptions(),
                    'style' => Examine::dictOptions('style')
                ],
            ])
            ->addColumn('message', '审核结果');
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['p.saas_appid', '=', $request->saas_appid]
        ];
        $name = $request->get('name');
        if ($name) {
            $where[] = ['p.name|p.title|p.mobile', 'like', "%{$name}%"];
        }
        $examine = $request->get('examine');
        if ($examine !== null) {
            $where[] = ['p.examine', '=', $examine];
        }
        $mch_id = $request->get('mch_id');
        if ($mch_id) {
            $where[] = ['p.mch_id', '=', $mch_id];
        }
        $data = MassageShop::where($where)
            ->alias('p')
            ->join('massage_user u', 'u.id = p.uid', 'LEFT')
            ->join('massage_mch m', 'm.id = p.mch_id')
            ->order('p.create_time desc')
            ->field('p.*,u.headimg,u.nickname,m.title as mch_title')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->uid) {
                    if ($item->nickname) {
                        $item->nickname = base64_decode($item->nickname);
                    }
                    if (strpos($item->headimg, 'http') !== 0) {
                        $item->headimg = UploadService::url($item->headimg);
                    }
                } else {
                    $item->nickname = '未委派店长';
                }
                if ($item->tel) {
                    $item->tel = implode('、', $item->tel);
                }
            });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {
        $saas_appid = $request->saas_appid;
        if ($request->method() === 'POST') {
            $D = $request->post();
            $tel = [];
            if ($D['tel1']) {
                $tel[] = $D['tel1'];
            }
            if ($D['tel2']) {
                $tel[] = $D['tel2'];
            }
            if ($D['tel3']) {
                $tel[] = $D['tel3'];
            }
            $D['tel'] = $tel;
            hpValidate(ValidateMassageShop::class, $D, 'admin_create');
            $MassageMch = MassageMch::where(['id' => $D['mch_id'], 'saas_appid' => $saas_appid, 'examine' => Examine::YES['value']])->find();
            if (!$MassageMch) {
                return $this->fail('商户不存在或未审核');
            }
            Db::startTrans();
            try {
                $mobile = $D['mobile'];
                $userModel = MassageUser::where(['mobile' => $mobile, 'saas_appid' => $saas_appid])->find();
                if (!$userModel) {
                    $userModel = new MassageUser;
                    $userModel->saas_appid = $saas_appid;
                    $userModel->mobile = $mobile;
                    $userModel->nickname = $D['title'] . '店长';
                    $userModel->password = $D['password'];
                    $userModel->headimg = $D['logo'][0];
                    $userModel->save();
                }
                $MassageShop = new MassageShop;
                $MassageShop->uid = $userModel->id;
                $MassageShop->saas_appid = $saas_appid;
                $MassageShop->mch_id = $D['mch_id'];
                $MassageShop->title = $D['title'];
                $MassageShop->logo = $D['logo'][0];
                $MassageShop->address = $D['address'];
                $MassageShop->examine = $D['examine'];
                $MassageShop->name = $D['name'];
                $MassageShop->mobile = $D['mobile'];
                $MassageShop->tel = $tel;
                list($province_id, $city_id, $area_id, $street_id) = $D['regions'];
                $MassageShop->province_id = (int)$province_id;
                $MassageShop->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageShop->city_id = $city_id;
                $MassageShop->city = MassageRegions::where(['id' => $city_id])->value('title');
                $MassageShop->area_id = $area_id;
                $MassageShop->area = MassageRegions::where(['id' => $area_id])->value('title');
                if ($street_id) {
                    $MassageShop->street_id = $street_id;
                    $MassageShop->street = MassageRegions::where(['id' => $street_id])->value('title');
                }
                $MassageShop->save();
                if (!empty($D['thumb'])) {
                    $MassageShopThumb = new MassageShopThumb;
                    $thumb = [];
                    foreach ($D['thumb'] as $key => $value) {
                        $temp = [
                            'shop_id' => $MassageShop->id,
                            'saas_appid' => $saas_appid,
                            'url' => $value,
                        ];
                        krsort($temp);
                        $thumb[] = $temp;
                    }
                    $MassageShopThumb->saveAll($thumb);
                }
                Db::commit();
                return $this->success('添加成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('mch_id', 'input', '商户ID', '', [
            'col' => 12,
        ]);
        $this->getFormBuilder($builder, $saas_appid);
        $builder->addDivider('负责人信息');
        $builder->addRow('name', 'input', '负责人', '', [
            'col' => 12,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
            'prompt' => [
                'text' => '手机号将作为登录账号，如已存在将直接关联',
            ],
        ]);
        $builder->addRow('password', 'input', '登录密码', '', [
            'col' => 12,
        ]);
        $builder->addDivider('门店图册');
        $builder->addComponent('thumb', 'uploadify', '门店图册', '', [
            'col' => 24,
            'props' => [
                'type' => 'image',
                'limit' => 99,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $saas_appid = $request->saas_appid;
        $MassageShop = MassageShop::where(['id' => $id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageShop) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $tel = [];
            if ($D['tel1']) {
                $tel[] = $D['tel1'];
            }
            if ($D['tel2']) {
                $tel[] = $D['tel2'];
            }
            if ($D['tel3']) {
                $tel[] = $D['tel3'];
            }
            $D['tel'] = $tel;
            $D['mch_id'] = $MassageShop->mch_id;
            hpValidate(ValidateMassageShop::class, $D, 'admin_update');
            Db::startTrans();
            try {
                $MassageShop->title = $D['title'];
                $MassageShop->logo = $D['logo'][0];
                $MassageShop->address = $D['address'];
                $MassageShop->examine = $D['examine'];
                $MassageShop->name = $D['name'];
                $MassageShop->mobile = $D['mobile'];
                $MassageShop->tel = $tel;
                list($province_id, $city_id, $area_id, $street_id) = $D['regions'];
                $MassageShop->province_id = (int)$province_id;
                $MassageShop->province = MassageRegions::where(['id' => $province_id])->value('title');
                $MassageShop->city_id = $city_id;
                $MassageShop->city = MassageRegions::where(['id' => $city_id])->value('title');
                $MassageShop->area_id = $area_id;
                $MassageShop->area = MassageRegions::where(['id' => $area_id])->value('title');
                if ($street_id) {
                    $MassageShop->street_id = $street_id;
                    $MassageShop->street = MassageRegions::where(['id' => $street_id])->value('title');
                } else {
                    $MassageShop->street_id = null;
                    $MassageShop->street = '';
                }
                $MassageShop->save();
                Db::commit();
                return $this->success('保存成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $this->getFormBuilder($builder, $saas_appid);
        $builder->addDivider('负责人信息');
        $builder->addRow('name', 'input', '负责人', '', [
            'col' => 12,
        ]);
        $builder->addRow('mobile', 'input', '手机号', '', [
            'col' => 12,
        ]);
        $regions = [
            $MassageShop->province_id,
            $MassageShop->city_id,
            $MassageShop->area_id
        ];
        if ($MassageShop->street_id) {
            $regions[] = $MassageShop->street_id;
        }
        $MassageShop->regions = $regions;
        if ($MassageShop->tel) {
            foreach ($MassageShop->tel as $key => $value) {
                $MassageShop->{'tel' . ($key + 1)} = $value;
            }
        }
        $data = $builder->setData($MassageShop)->create();
        return $this->successRes($data);
    }
    public function getFormBuilder($builder, $saas_appid)
    {
        $builder->addRow('title', 'input', '门店名称', '', [
            'col' => 12,
        ]);
        $builder->addComponent('logo', 'uploadify', '门店logo', '', [
            'col' => 12,
            'props' => [
                'type' => 'image',
                'limit' => 1,
                'format' => ['jpg', 'jpeg', 'png']
            ],
        ]);
        $builder->addRow('tel1', 'input', '门店联系电话1', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel2', 'input', '门店联系电话2', '', [
            'col' => 12,
        ]);
        $builder->addRow('tel3', 'input', '门店联系电话3', '', [
            'col' => 12,
        ]);
        $regions = MassageRegions::getCache($saas_appid);
        $builder->addRow('regions', 'city', '地区', [], [
            'col' => 12,
            'options' => $regions,
            'props' => [
                'filterable' => true,
                'placeholder' => '请选择地区',
                'clearable' => true,
                'props' => [
                    'value' => 'id',
                    'label' => 'title',
                    'children' => 'children'
                ]
            ]
        ]);
        $builder->addRow('address', 'input', '详细地址', '', [
            'col' => 12,
        ]);
        $builder->addRow('examine', 'radio', '状态', Examine::WAIT['value'], [
            'col' => 12,
            'options' => Examine::getOptions(),
        ]);
    }
    public function examine(Request $request)
    {
        $id = $request->get('id');
        $MassageShop = MassageShop::where(['id' => $id, 'saas_appid' => $request->saas_appid, 'examine' => Examine::WAIT['value']])->find();
        if (!$MassageShop) {
            return $this->fail('数据不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $MassageShop->examine = $D['examine'];
            Db::startTrans();
            try {
                if (!in_array($MassageShop->examine, [Examine::YES['value'], Examine::NO['value']])) {
                    throw new \Exception('请选择审核状态');
                }
                if ($MassageShop->examine == Examine::NO['value']) {
                    if (empty($D['message'])) {
                        throw new \Exception('请填写驳回理由');
                    }
                    $MassageShop->message = $D['message'];
                } else {
                    $MassageShop->message = '通过';
                }
                $MassageShop->save();
                if ($D['thumb_examine'] == Examine::YES['value']) {
                    $thumb = MassageShopThumb::where(['shop_id' => $MassageShop->id, 'saas_appid' => $MassageShop->saas_appid])->select();
                    foreach ($thumb as $key => $itme) {
                        $itme->examine = Examine::YES['value'];
                        $itme->save();
                    }
                }
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail($th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addComponent('logo', 'el-image', '门店LOGO', '', [
            'col'           => 6,
            'props'         => [
                'src'       => $MassageShop->logo,
                'width'     => 160,
                'height'    => 220
            ]
        ]);
        $builder->addComponent('id', 'info', '门店ID', '', [
            'col'           => 4,
        ]);
        $builder->addComponent('title', 'info', '门店名称', '', [
            'col'           => 14,
        ]);
        foreach ($MassageShop->tel as $key => $value) {
            $builder->addComponent('tel' . ($key + 1), 'info', '门店联系电话' . ($key + 1), $value, [
                'col'           => 8,
            ]);
        }
        $builder->addDivider('门店详细地址');
        $address_info = [
            $MassageShop->province,
            $MassageShop->city,
            $MassageShop->area,
        ];
        if ($MassageShop->street) {
            $address_info[] = $MassageShop->street;
        }
        $address_info[] = $MassageShop->address;
        $builder->addComponent('address_info', 'info', '', implode(" ", $address_info), [
            'col'           => 24,
        ]);
        $builder->addDivider('门店负责人信息');
        $builder->addComponent('name', 'info', '负责人', '', [
            'col'           => 6,
        ]);
        $builder->addComponent('mobile', 'info', '负责人电话', '', [
            'col'           => 6,
        ]);
        $builder->addDivider('门店图册');
        $builder->addRow('thumb_examine', 'radio', '门店图册状态', 0, [
            'col' => 24,
            'options' => Examine::getOptions()
        ]);
        $thumb = MassageShopThumb::where(['mch_id' => $MassageShop->id, 'saas_appid' => $MassageShop->saas_appid])->field('url')->select();
        foreach ($thumb as $key => $itme) {
            $builder->addComponent('thumb_' . $key, 'el-image', '', '', [
                'col'           => 4,
                'props'         => [
                    'src'       => $itme->url,
                    'width'     => 160,
                    'height'    => 220
                ]
            ]);
        }
        $builder->addDivider('审核');
        $builder->addRow('examine', 'radio', '状态', Examine::YES['value'], [
            'col' => 24,
            'options' => Examine::getOptions(),
            'control' => [
                [
                    'value' => Examine::NO['value'],
                    'where' => '==',
                    'rule' => [
                        Elm::textarea('message', '驳回理由')
                            ->col([
                                'span' => 24
                            ])
                            ->props([
                                'filterable' => true,
                                'placeholder' => '请输入驳回理由',
                            ])
                    ],
                ],
            ]
        ]);
        $data = $builder->setData($MassageShop)->create();
        return $this->successRes($data);
    }
    public function control(Request $request)
    {
        $MassageShop = MassageShop::where(['id' => $request->get('id'), 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageShop) {
            return $this->fail('数据不存在');
        }
        $UserModel = MassageUser::where(['id' => $MassageShop->uid])->find();
        if (!$UserModel) {
            return $this->fail('数据不存在');
        }
        if(!$UserModel->mobile){
            return $this->fail('请先绑定用户手机号');
        }
        Session::set($request->plugin . '_shop', $UserModel);
        $token = Str::random(32);
        return $this->successRes([
            'url' => $this->pluginPrefix . '/shop/#/?appid=' . $request->saas_appid . '&token=' . $token
        ]);
    }
}
